package com.yuanshi.food.common.config;

import cn.hutool.core.text.CharSequenceUtil;
import com.yuanshi.food.common.entity.Response;
import com.yuanshi.food.common.enums.ResponseCodeEnum;
import com.yuanshi.food.common.exception.AppException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理程序
 *
 * @author wcy
 * @date 2024/11/26
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionConfig {
    /**
     * 处理方法论点不有效例外
     *
     * @param ex      前任
     * @param request 请求
     * @return {@link Response }<{@link Void }>
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex, HttpServletRequest request) {
        BindingResult result = ex.getBindingResult();
        FieldError fieldError = result.getFieldError();
        String errorMessage = CharSequenceUtil.EMPTY;
        if (fieldError != null) {
            errorMessage = fieldError.getDefaultMessage();
        }
        log.error("应用层异常, url :{}", request.getRequestURI(), ex);
        return Response.getResponseVoid(ResponseCodeEnum.UN_ERROR.getCode(), errorMessage);
    }

    /**
     * 处理应用层异常
     *
     * @param ex ex
     * @return {@link Response }<{@link String }>
     */
    @ExceptionHandler(AppException.class)
    public Response<String> handleAppException(AppException ex, HttpServletRequest request) {
        log.error("应用层异常, url :{}", request.getRequestURI(), ex);
        return Response.appException(ex);
    }

    /**
     * 处理系统异常
     *
     * @param ex ex
     * @return {@link Response }<{@link String }>
     */
    @ExceptionHandler(Exception.class)
    public Response<String> handleSystemException(Exception ex, HttpServletRequest request) {
        log.error("系统异常, url :{}", request.getRequestURI(), ex);
        return Response.build(ResponseCodeEnum.SYSTEM_EXCEPTION, ex.getMessage());
    }

    /**
     * 处理登录鉴权异常
     *
     * @param ex ex
     * @return {@link Response }<{@link String }>
     */
//    @ExceptionHandler(NotLoginException.class)
//    public Response<String> handleAuthException(NotLoginException ex, HttpServletRequest request) {
//        log.error("鉴权异常, url :{}", request.getRequestURI(), ex);
//        return Response.fail(ex.getMessage(), request.getRequestURI());
//    }

}